﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace AudioCore.Common
{
    public class ProcessUtils
    {
        //20100226 - ThanhLT Fix bug: TraceSource logs error - Start
        //#if TEST
        //        protected static TraceLog _ts = new TraceLog(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name, SourceLevels.All);
        //#else
        //        protected static TraceLog _ts = new TraceLog(System.Reflection.Assembly.GetEntryAssembly().ManifestModule.Name, SourceLevels.All);
        //#endif
        protected static TraceLog _ts = new TraceLog(Constant.TraceSourceName.General, SourceLevels.All);
        //20100226 - ThanhLT Fix bug: TraceSource logs error - End

        public static int ExecuteFile(string filePath, string arg)
        {
            _ts.TraceInformation(string.Format("Execute file '{0}' with arg={1} :: BEGIN", filePath, arg));
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
                return -1;

            Process p = new Process();
            try
            {
                FileInfo file = new FileInfo(filePath);
                string directory = file.DirectoryName;
                p.StartInfo.WorkingDirectory = directory;
                p.StartInfo.FileName = filePath;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.Arguments = arg;
                p.StartInfo.UseShellExecute = false;
                p.Start();
            }
            catch (Exception ex)
            {
                // Write error to log file
                _ts.TraceError(ex.ToString());
                return -1;
            }

            _ts.TraceInformation(string.Format("Execute file '{0}' with arg={1} :: END", filePath, arg));

            return 0;
        }

        /// <summary>
        /// Search one assemply in a list with CodeBase = dllPath
        /// </summary>
        /// <param name="list"></param>
        /// <param name="dllPath"></param>
        /// <returns></returns>
        public static Assembly GetAssembly(Assembly[] list, string dllPath)
        {
            foreach (Assembly a in list)
            {
                if (a.CodeBase.Replace("file:///", "").Equals(dllPath.Replace("\\","/"), StringComparison.InvariantCultureIgnoreCase))
                {
                    return a;
                }
            }
            return null;
        }

        public static void ExecuteBrowser(string arg)
        {
            System.Diagnostics.Process.Start("IExplore.exe", arg);
        }
    }
}
